package com.zzyl.service.impl;

import com.zzyl.dto.BedDto;
import com.zzyl.entity.Bed;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.BedMapper;
import com.zzyl.mapper.RoomTypeMapper;
import com.zzyl.service.BedService;
import com.zzyl.vo.BedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BedServiceImpl implements BedService {

    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private RoomTypeMapper roomTypeMapper;

    @Override
    public List<BedVo> getBedsByRoomId(Long roomId) {
        return bedMapper.getBedsByRoomId(roomId);
    }

    //新增床位
    @Override
    public void insert(BedDto bedDto) {
        //床位编码不可重复
        Bed repeatBed = bedMapper.getBedByBedNumber(bedDto.getBedNumber()); //where bed_number=bedNumber
        if (repeatBed != null) { //查到与当前要新增的编号相同的床位信息
            throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPEAT_BED_NUMBER);
        }
        //新增床位
        Bed bed = new Bed();
        BeanUtils.copyProperties(bedDto,bed);
        bed.setBedStatus(0);
        bedMapper.insertBed(bed);
        //增加房间类型（room_type）对应的床位数(bed_count)
        roomTypeMapper.updateCount(bed.getRoomId());
    }

    //根据ID查询床位信息
    @Override
    public BedDto getBedById(Integer id) {
        BedDto bedDto = bedMapper.selectById(id);
        Bed bed = new Bed();
        BeanUtils.copyProperties(bedDto,bed);
        return bedDto;
    }

    //更新床位信息
    @Override
    public void updateBed(BedDto bedDto) {
        //不可修改非空闲的床位信息（前端未传递状态信息，只能拿到id查询出状态）
         Long status = bedMapper.getBedStatus(bedDto.getId());
         if (status != 0) {
             throw new BaseException(BasicEnum.BED_EDIT_FAIL_INUSE);
         }
         //修改的床位编号不能与已有的重复（须排除不修改编号时的情况【查询须排除自身】）
        Long count = bedMapper.getSameBedNumberCount(bedDto.getBedNumber(),bedDto.getId());
         if (count > 0) {
             throw new BaseException(BasicEnum.BED_INSERT_FAIL_REPEAT_BED_NUMBER);
         }
         //修改床位信息
        Bed bed = new Bed();
        BeanUtils.copyProperties(bedDto,bed);
        bedMapper.update(bed);
    }

    //删除床位
    @Override
    public void deleteById(Integer id) {
        //不可删除非空闲的床位
        Long status = bedMapper.getBedStatusToDel(id);
        if (status != 0) {
            throw new BaseException(BasicEnum.BED_EDIT_FAIL_INUSE);
        }
        BedDto bedDto = bedMapper.selectById(id);
        if(bedDto!=null){
            //删除床位
            bedMapper.delete(id);
            //减少房间类型（room_type）对应的床位数(bed_count）
            roomTypeMapper.downCount(bedDto.getRoomId());
        }
    }

}

